package com.the_last.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.the_last.mapper.UserMapper;
import com.the_last.pojo.dto.UserDTO;
import com.the_last.pojo.po.User;
import com.the_last.pojo.vo.UserVO;
import com.the_last.service.IUserService;
import com.the_last.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    
    private final PasswordEncoder passwordEncoder;
    
    @Override
    public Result<Page<UserVO>> getUserList(Page<User> page, UserDTO userDTO) {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            
            // 查询条件
            if (StringUtils.hasText(userDTO.getUserName())) {
                queryWrapper.like(User::getUserName, userDTO.getUserName());
            }
            if (StringUtils.hasText(userDTO.getPhone())) {
                queryWrapper.like(User::getPhone, userDTO.getPhone());
            }
            if (userDTO.getStatus() != null) {
                queryWrapper.eq(User::getStatus, userDTO.getStatus());
            }
            
            // 排除已删除的用户
            queryWrapper.eq(User::getDeleted, 0);
            queryWrapper.orderByDesc(User::getCreatedTime);
            
            Page<User> userPage = page(page, queryWrapper);
            
            // 转换为VO
            Page<UserVO> voPage = new Page<>();
            BeanUtils.copyProperties(userPage, voPage, "records");
            
            List<UserVO> userVOList = new ArrayList<>();
            for (User user : userPage.getRecords()) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                userVOList.add(userVO);
            }
            voPage.setRecords(userVOList);
            
            return Result.success(voPage);
            
        } catch (Exception e) {
            log.error("获取用户列表失败", e);
            return Result.fail("获取用户列表失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> addUser(UserDTO userDTO) {
        try {
            // 检查用户名是否已存在
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUserName, userDTO.getUserName())
                       .eq(User::getDeleted, 0);
            
            if (count(queryWrapper) > 0) {
                return Result.fail("用户名已存在");
            }
            
            // 检查手机号是否已存在
            queryWrapper.clear();
            queryWrapper.eq(User::getPhone, userDTO.getPhone())
                       .eq(User::getDeleted, 0);
            
            if (count(queryWrapper) > 0) {
                return Result.fail("手机号已存在");
            }
            
            User user = new User();
            BeanUtils.copyProperties(userDTO, user);
            
            // 加密密码
            if (StringUtils.hasText(userDTO.getPassword())) {
                user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
            } else {
                // 默认密码
                user.setPassword(passwordEncoder.encode("123456"));
            }
            
            user.setCreatedTime(LocalDateTime.now());
            user.setUpdatedTime(LocalDateTime.now());
            user.setDeleted(0);
            
            boolean success = save(user);
            return success ? Result.success() : Result.fail("添加用户失败");
            
        } catch (Exception e) {
            log.error("添加用户失败", e);
            return Result.fail("添加用户失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateUser(UserDTO userDTO) {
        try {
            if (userDTO.getId() == null) {
                return Result.fail("用户ID不能为空");
            }
            
            User existUser = getById(userDTO.getId());
            if (existUser == null || existUser.getDeleted().equals(1)) {
                return Result.fail("用户不存在");
            }
            
            // 检查用户名是否已被其他用户使用
            if (!existUser.getUserName().equals(userDTO.getUserName())) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getUserName, userDTO.getUserName())
                           .eq(User::getDeleted, 0)
                           .ne(User::getId, userDTO.getId());
                
                if (count(queryWrapper) > 0) {
                    return Result.fail("用户名已存在");
                }
            }
            
            // 检查手机号是否已被其他用户使用
            if (!existUser.getPhone().equals(userDTO.getPhone())) {
                LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(User::getPhone, userDTO.getPhone())
                           .eq(User::getDeleted, 0)
                           .ne(User::getId, userDTO.getId());
                
                if (count(queryWrapper) > 0) {
                    return Result.fail("手机号已存在");
                }
            }
            
            User user = new User();
            BeanUtils.copyProperties(userDTO, user);
            user.setUpdatedTime(LocalDateTime.now());
            
            // 不更新密码（使用单独的重置密码接口）
            user.setPassword(null);
            
            boolean success = updateById(user);
            return success ? Result.success() : Result.fail("更新用户失败");
            
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return Result.fail("更新用户失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> deleteUser(Long userId) {
        try {
            User user = getById(userId);
            if (user == null || user.getDeleted().equals(1)) {
                return Result.fail("用户不存在");
            }
            
            // 软删除
            user.setDeleted(1);
            user.setUpdatedTime(LocalDateTime.now());
            
            boolean success = updateById(user);
            return success ? Result.success() : Result.fail("删除用户失败");
            
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.fail("删除用户失败");
        }
    }
    
    @Override
    public Result<UserVO> getUserById(Long userId) {
        try {
            User user = getById(userId);
            if (user == null || user.getDeleted().equals(1)) {
                return Result.fail("用户不存在");
            }
            
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            
            return Result.success(userVO);
            
        } catch (Exception e) {
            log.error("获取用户详情失败", e);
            return Result.fail("获取用户详情失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateUserStatus(List<Long> userIds, Integer status) {
        try {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(User::getId, userIds)
                       .eq(User::getDeleted, 0);
            
            User updateUser = new User();
            updateUser.setStatus(status);
            updateUser.setUpdatedTime(LocalDateTime.now());
            
            boolean success = update(updateUser, queryWrapper);
            return success ? Result.success() : Result.fail("更新用户状态失败");
            
        } catch (Exception e) {
            log.error("更新用户状态失败", e);
            return Result.fail("更新用户状态失败");
        }
    }
    
    @Override
    @Transactional
    public Result<Void> resetPassword(Long userId, String newPassword) {
        try {
            User user = getById(userId);
            if (user == null || user.getDeleted().equals(1)) {
                return Result.fail("用户不存在");
            }
            
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdatedTime(LocalDateTime.now());
            
            boolean success = updateById(user);
            return success ? Result.success() : Result.fail("重置密码失败");
            
        } catch (Exception e) {
            log.error("重置密码失败", e);
            return Result.fail("重置密码失败");
        }
    }
}